package com.share.cloudStorage.files.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.share.cloudStorage.files.model.Files;
import com.share.cloudStorage.files.model.FilesQueryParams;
import com.share.cloudStorage.files.service.FilesService;
import com.share.cloudStorage.filter.SecurityFilter;
import com.share.cloudStorage.folders.service.FoldersService;
import com.share.cloudStorage.hdfs.HdfsClient;
import com.share.cloudStorage.model.Result;
import com.share.cloudStorage.recycle.model.Recycle;
import com.share.cloudStorage.recycle.service.RecycleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;

import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/v1/files")
@Slf4j
public class FilesController {
    public static Map<String, Integer> downloadProgressMap = new ConcurrentHashMap<>();

    @Autowired
    private FilesService filesService;
    @Autowired
    private FoldersService foldersService;
    @Autowired
    private HdfsClient hdfsClient;

    @Autowired
    private RecycleService recycleService;

    //查询文件通过id
    @RequestMapping("/searchFilesById")
    public List<Files> searchFilesById(@RequestBody FilesQueryParams filesQueryParams){
        return filesService.searchFilesById(filesQueryParams);
    }
    @PostMapping("/deleteFiles")
    public Result deleteFiles(@RequestParam("deleteIds") int[] ids){
        String msg = filesService.deleteFiles(ids);
        return Result.ok(msg);
    }
    @PostMapping("/updateFilesIsDelete")
    public Result updateFilesIsDelete(@RequestBody Files files){
        String msg = filesService.updateFilesIsDelete(files);
        return Result.ok(msg);
    }
    //下载文件
    @PostMapping("/downLoadFile")
    public void downLoadFile(@RequestBody Files files,HttpServletResponse response) throws IOException, InterruptedException {
        ResponseEntity<byte[]> responseEntity;
        log.info("files:{}",files);
        Boolean isFolder = files.getIsFolder();
        String folderName = foldersService.getFolderNameById(files.getUserId());
        String path = "/"+folderName+"/"+files.getFilePath();
        if (!isFolder){
            hdfsClient.downLoad(path,response);
        }else {
            log.info("files.getTaskId:{}",files.getTaskId());
            hdfsClient.downloadHdfsZip(path,response,downloadProgressMap, files.getTaskId());
        }

    }
    //获取唯一的uuid(任务id)
    @GetMapping("/getTaskId")
    public Result getTaskId() {
        String taskId = UUID.randomUUID().toString(); // 生成一个唯一的任务ID
        downloadProgressMap.put(taskId, 0);
        return Result.ok(taskId); // 返回下载进度
    }
    // 获取下载进度
    @PostMapping("/download-progress")
    public Integer getDownloadProgress(@RequestParam("taskId") String taskId) {
        log.info("taskId:{}",taskId);
        Integer progress = downloadProgressMap.get(taskId);
        log.info("progress:{}",progress);
        return progress; // 返回下载进度
    }

    //将文件放入回收站
    @GetMapping("/fileRecycle")
    @Transactional
    public void fileRecycle(@RequestParam String fileIds){
        String[] split= fileIds.split(",");
        List<Integer> fileIdList = Arrays.stream(split)
                .map(Integer::parseInt) // 将字符串转换为整数
                .collect(Collectors.toList());
        filesService.recycleByIds(fileIdList);

        QueryWrapper<Files> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().in(Files::getFileId,fileIdList);
        List<Files> list = filesService.list(queryWrapper);
        List<Recycle> recycleList = new ArrayList<>();
        for (Files files : list) {
            Recycle recycle = new Recycle();
            recycle.setUserId(SecurityFilter.userid.get());
            recycle.setFileId(files.getFileId());
            recycle.setOriginalPath(files.getFilePath());
            recycle.setIsRestored(0);
            recycleList.add(recycle);
        }
        recycleService.saveBatch(recycleList);
    }


    //查询文件
    @PostMapping("searchVisibleFilesById")
    public List<Files> searchVisibleFilesById(@RequestBody FilesQueryParams filesQueryParams){
        return filesService.searchVisibleFilesById(filesQueryParams);
    }

    //上传文件
    @PostMapping("/uploadFile")
    public Result uploadFile(@RequestPart("file")MultipartFile file,@RequestPart("files") Files files) throws IOException {
        return filesService.uploadFile(file,files);
    }

    //重命名文件
    @PostMapping("/reName")
    public Result reName(@RequestBody Files files){
        return filesService.reName(files);
    }
    //新建文件夹
    @PostMapping("/createFolder")
    public Result createFolder(@RequestBody Files files){
        return filesService.createFolder(files);
    }

}

